﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using EnvDTE;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.Shell;
using Microsoft.Win32;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

namespace SP2010DevExtensions.Helper
{
    public class SharePointMappingFolderHelper
    {
        public static void EnsureISAPIFolderExists(Project project)
        {
            var dteType = project.DTE; //(DTE)Package.GetGlobalService(typeof(DTE));

            var globalOleServiceProvider = (IOleServiceProvider)dteType;
            var globalServiceProvider = new ServiceProvider(globalOleServiceProvider);
            var shareProjectService = (ISharePointProjectService)globalServiceProvider.GetService(typeof(ISharePointProjectService));
            var sharePointProject = shareProjectService.Convert<Project, ISharePointProject>(project);

            if (sharePointProject != null)
            {
                var layoutFolder = sharePointProject.MappedFolders.Where(mf => mf.FolderType == MappedFolderType.SharePointRoot).FirstOrDefault();
                if (layoutFolder == null)
                {
                    var rootFolder = sharePointProject.MappedFolders.Add(MappedFolderType.SharePointRoot);
                    var pi = shareProjectService.Convert<ISharePointProjectItem, ProjectItem>(rootFolder);
                    pi.ProjectItems.AddFolder("ISAPI");
                }
            }
        }
        public static ProjectItem ConvertProjectItem(IMappedFolder mappedFolder)
        {
            var project= mappedFolder.Project.ProjectService.Convert<ISharePointProject, Project>(mappedFolder.Project);
            var dteType =project.DTE; //(DTE)Package.GetGlobalService(typeof(DTE));

            var globalOleServiceProvider = (IOleServiceProvider)dteType;
            var globalServiceProvider = new ServiceProvider(globalOleServiceProvider);
            var shareProjectService = (ISharePointProjectService)globalServiceProvider.GetService(typeof(ISharePointProjectService));
            return shareProjectService.Convert<ISharePointProjectItem, ProjectItem>(mappedFolder);
        }
        

    }
}
